<script setup>
import { reactive, ref,defineEmits } from 'vue'
import { checkMobile, checkPassword } from '@/utils/validate'
import {saveApi,updateApi} from "../../../api/user";
import {ElMessage} from "element-plus";
//自定义事件
const emit = defineEmits(['flush']);
// 表单数据
const formData = ref({
  id: 0,
  username: '',
  password: '',
  no: ''
})
// 表单验证
const formRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { validator: checkPassword, message: '请输入6~12个字符', trigger: 'blur' }
  ],
  no: [
    { required: true, message: '请输入工号', trigger: 'blur' }
  ]
})
// 提交验证
const formRef = ref()
const onSubmit = () => {
  formRef.value.validate(async (isSuccess) => {
    if (isSuccess) {
      //请求接口
      var r;
      var isadd=formData.value.id==0||formData.value.id==undefined
      if(isadd){
        //新增
        r=await saveApi(formData.value);
      }else {
        //修改
        r=await updateApi(formData.value);
      }
      if(r.code==0){
        state.value=false;
        ElMessage({
          type: 'success',
          message: isadd?'新增用户成功':"修改用户成功"})
        emit('flush');
      }else {
        ElMessage.error(r.data)
      }
    }
  })
}

// 对话框状态
const state = ref(false)
// 暴露
defineExpose({
  state,
  formData
})
</script>
<template>
  <el-dialog
    v-model="state"
    :title="`${formData.id!=undefined ? '修改' : '新增'}用户`"
    width="600"
    :before-close="() => (state = false)"
  >
    <!-- 内容 -->
    <el-form
      v-if="state"
      size="large"
      label-width="80"
      :model="formData"
      :rules="formRules"
      ref="formRef"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input placeholder="请输入用户名" v-model="formData.username" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="密码" prop="password">
            <el-input placeholder="请输入密码" type="password" show-password v-model="formData.password" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="工号" prop="no">
            <el-input placeholder="请输入工号" v-model="formData.no" />
          </el-form-item>
        </el-col>

      </el-row>
      <el-form-item label="">
        <el-button type="primary" @click="onSubmit">确定</el-button>
        <el-button type="default" @click="state = false">取消</el-button>
      </el-form-item>
    </el-form>
    <!-- 内容 -->
  </el-dialog>
</template>
